package com.cabrida.livestar.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.content.ClipboardManager;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.widget.EditText;

public class StringUtils {

	/**
	 * To determine whether a string is empty or length to 0 or consists of
	 * blank
	 * 
	 * @param str
	 * @return if string is null or its size is 0 or it is made by space, return
	 *         true, else return false.
	 */
	public static boolean isBlank(String str) {
		if (str == null || str.trim().length() == 0 || str.trim().equals("null")) {
			return true;
		}
		return false;
	}

	/**
	 * To determine whether a string is empty or length is 0
	 * 
	 * @param str
	 * @return if string is null or its size is 0, return true, else return
	 *         false.
	 */
	public static boolean isEmpty(String s) {
		if (s == null || s.trim().length() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * Check a string is composed of Numbers
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNum(String str) {
		final String regEx = "^[0-9]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * Check a string is composed of letters
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEnglish(String str) {
		final String regEx = "^[a-zA-Z]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * Checks if a string is letters or Numbers
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumOrEng(String str) {
		final String regEx = "^[0-9a-zA-Z]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * Check a string is composed of letters or characters
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChOrEng(String str) {
		final String regEx = "^[\u4e00-\u9fa5a-zA-Z]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * Check a string is characters
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isChinese(String str) {
		final String regEx = "^[\u4e00-\u9fa5]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	// 判断是否为手机号
	public static boolean isPhone(String inputText) {
		Pattern p = Pattern.compile("1[1|2|3|4|5|6|7|8|9|][0-9]{9}");
		Matcher m = p.matcher(inputText);
		return m.matches();
	}

	/**
	 * 判断是否为电话或手机号
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isCallNum(String phone) {
		Pattern p = Pattern.compile(
				"^((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)");
		Matcher m = p.matcher(phone);
		return m.matches();
	}

	// 判断格式是否为email
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	// 判断格式是否为字母加数字
	public static boolean isPass(String num) {
		// String str = "[a-zA-Z_0-9]{6,20}";
		// String str = "^(?!([^A-Za-z]|\\d)+$)[a-zA-Z\\d]{6,20}$";
		String str = "(?!^\\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{6,20}";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(num);
		return m.matches();
	}

	/**
	 * Checks if a string is the PostCode
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isPostCode(String postCode) {
		Pattern p = Pattern.compile("^[0-9]{1}(\\d+){5}$");
		Matcher m = p.matcher(postCode);
		return m.matches();
	}

	/**
	 * encoded in utf-8
	 * 
	 * <pre>
	 * utf8Encode(null)        =   null
	 * utf8Encode("")          =   "";
	 * utf8Encode("aa")        =   "aa";
	 * utf8Encode("中文")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
	 * </pre>
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 *             if an error occurs
	 */
	public static String utf8Encode(String str) {
		if (!isEmpty(str) && str.getBytes().length != str.length()) {
			try {
				return URLEncoder.encode(str, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
			}
		}
		return str;
	}

	/**
	 * encoded in utf-8, if exception, return defultReturn
	 * 
	 * @param str
	 * @param defultReturn
	 * @return
	 */
	public static String utf8Encode(String str, String defultReturn) {
		if (!isEmpty(str) && str.getBytes().length != str.length()) {
			try {
				return URLEncoder.encode(str, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				return defultReturn;
			}
		}
		return str;
	}

	static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String clean(String s) {
		int startIndex = s.indexOf('"');
		int endIndex = s.lastIndexOf('"');

		if (startIndex >= 0 && endIndex > startIndex) {
			return s.substring(startIndex + 1, endIndex).trim();
		}

		return s;
	}

	/**
	 * get hex string of specified bytes
	 */
	public static String toHexString(byte[] bytes, int off, int len) {
		if (bytes == null)
			throw new NullPointerException("bytes is null");
		if (off < 0 || (off + len) > bytes.length)
			throw new IndexOutOfBoundsException();
		char[] buff = new char[len * 2];
		int v;
		int c = 0;
		for (int i = 0; i < len; i++) {
			v = bytes[i + off] & 0xff;
			buff[c++] = HEX_CHARS[(v >> 4)];
			buff[c++] = HEX_CHARS[(v & 0x0f)];
		}
		return new String(buff, 0, len * 2);
	}

	/**
	 * Remove the blank in the string
	 * 
	 * @param str
	 * @return Remove Spaces after the string
	 */
	public static String removeBlank(String s) {
		if (isEmpty(s)) {
			return "";
		}
		StringBuffer r = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
				r.append(s.charAt(i));
			}
		}
		return r.toString();
	}

	/**
	 * Check whether contain special characters
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceSpecial(String str) {
		String result = "";
		final String regEx = "[^,.!?:%#$@0-9a-zA-Z_\u4e00-\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		result = m.replaceAll("");
		return result;
	}

	/**
	 * Check whether contain special characters
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceSpecialNum(String str) {
		String result = "";
		final String regEx = "[^,.!?:%#$@a-zA-Z_\u4e00-\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		result = m.replaceAll("");
		return result;
	}

	/**
	 * Check whether contain special characters
	 * 
	 * @param str
	 * @return
	 */
	public static boolean containSpecial(String str) {
		final String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#�?%…�??&*（）—�??+|{}‘；：�?��?��?��?�，、？\u4e00-\u9fa5a-zA-Z]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/*
	 * Java文件操作 获取文件扩展�?
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/*
	 * Java文件操作 获取不带扩展名的文件�?
	 */
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

	// float类型数据，保留x位小�?(如保留小数点后两位小数，str格式�? ".00")
	public static String getFloatDecimalPoint(float number, String str) {
		DecimalFormat decimalFormat = new DecimalFormat(str);// 构�?�方法的字符格式这里如果小数不足2�?,会以0补足.
		return decimalFormat.format(number);
	}

	// 小数点后保留2位小数
	public static String getFloatDecimalPoint(Long str) {
		DecimalFormat df = new DecimalFormat("#0.00");
		double defund = (double) str;
		return df.format(defund);
	}

	public static void lockEditText(EditText editText, boolean value) {
		if (value) {
			editText.setFilters(new InputFilter[] { new InputFilter() {
				@Override
				public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
						int dend) {
					return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
				}
			} });
		} else {
			editText.setFilters(new InputFilter[] { new InputFilter() {
				@Override
				public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
						int dend) {
					return null;
				}
			} });
		}
	}

	/**
	 * 将文本复制到剪贴板 add by feng.G
	 * 
	 * @param content
	 */
	@SuppressWarnings("deprecation")
	public static void copy(String content, Context context) {
		// 得到剪贴板管理器
		ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(content.trim());
	}

	/**
	 * 实现粘贴功能 add by feng.G
	 * 
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String paste(Context context) {
		// 得到剪贴板管理器
		ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		return cmb.getText().toString().trim();
	}

	public static void setPricePoint(final EditText editText) {
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().contains(".")) {
					if (s.length() - 1 - s.toString().indexOf(".") > 2) {
						s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
						editText.setText(s);
						editText.setSelection(s.length());
					}
				}
				if (s.toString().trim().substring(0).equals(".")) {
					s = "0" + s;
					editText.setText(s);
					editText.setSelection(2);
				}

				if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
					if (!s.toString().substring(1, 2).equals(".")) {
						editText.setText(s.subSequence(0, 1));
						editText.setSelection(1);
						return;
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	/**
	 * 验证身份证号是否合法方法
	 * 
	 * @param idCard
	 * @return
	 */
	public static boolean isValidateIdCard(String idCard) {
		// 15位和18位身份证号码的正则表达式
		String regIdCard = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
		Pattern p = Pattern.compile(regIdCard);
		return p.matcher(idCard).matches();
	}

	/**
	 * . 功能：判断字符串是否为日期格式
	 * 
	 * @param strDate
	 *            strDate
	 * @return boolean boolean
	 */
	public static boolean isDate(String strDate) {
		Pattern pattern = Pattern.compile(
				"^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Matcher m = pattern.matcher(strDate);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 钱数金额格式化
	 * 
	 * @param money
	 * @return
	 */
	public static String fomatMoney(double money) {
		DecimalFormat myformat = new DecimalFormat();
		if (money == 0) {
			return "0.00";
		} else {
			myformat.applyPattern("##,##0.00");
			return myformat.format(money);
		}
	}

	// 判断是否是表情
	public static boolean isNumeric(String str) {
		if (str != null && str.length() > 0) {
			String string = str.toString().trim();
			boolean digit = Character.isDigit(string.charAt(0));
			if (digit && string.length() > 3) {
				String subSequence = string.substring(3, string.length());
				if (subSequence.toString().length() > 0) {
					return false;
				}
			}
			return digit;
		} else {
			return false;
		}
	}

	public static String replaceEmoji(String str) {
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
				Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(str);
		return emojiMatcher.replaceAll("");
	}

	static boolean isShowToast = true;

	public static boolean isContainEmoji(Context ctx, String str) {
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
				Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(str);
		boolean is = emojiMatcher.find();
		// if (is && isShowToast) {
		// isShowToast = false;
		// Toast.makeText(ctx, "暂不支持输入法自带表情", Toast.LENGTH_LONG).show();
		// }
		// new Handler().postDelayed(new Runnable() {
		// public void run() {
		// isShowToast = true;
		// }
		// }, 2000);
		return is;
		// return emojiMatcher.replaceAll("");
	}

	/**
	 * 使用java正则表达式去掉多余的.与0
	 * 
	 * @param s
	 * @return
	 */
	public static String subZeroAndDot(String s) {
		if (s.indexOf(".") > 0) {
			s = s.replaceAll("0+?$", "");// 去掉多余的0
			s = s.replaceAll("[.]$", "");// 如最后一位是.则去掉
		}
		return s;
	}

	/**
	 * 保留两位小数
	 */
	public static String reservedDecimal(double d) {
		DecimalFormat df = new DecimalFormat("#####0.00");
		return df.format(d);
	}

	// EditText只能输入url
	public static String stringFilter(String str) throws PatternSyntaxException {
		String regEx = "[^a-zA-Z0-9/:.~!@#$%^&*_=+?]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	//格式化省市区地址
	public static String AddressReplaceStr(String str) {
		String s = str.substring(0, 2);
		if (s.equals("北京") || s.equals("上海") || s.equals("天津") || s.equals("重庆")) {
			if (str.substring(2, 3).equals("县")) {
				return str.replace("县", "");
			} else if (str.substring(2, 5).equals("市辖区")) {
				return str.replace("市辖区", "");
			} else if (str.substring(2, 3).equals("市")) {
				return str.replace("市", "");
			} else {
				return str.substring(0, 2) + str.substring(4);
			}
		} else {
			return str;
		}
	}
}